package src.com.neusoft.nep.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import src.com.neusoft.nep.common.AlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AssignGridWorkersViewController {
    @FXML
    private TableView<FeedbackData> tableView1;
    @FXML
    private TableView<DetailedAddress> tableView2;
    @FXML
    private TableColumn<FeedbackData, String> colFeedbackerName, colEstPollutionLevel, colFeedbackDate, colPhoneNumber,colProvince,colCity,colDetails;
    @FXML
    private TableColumn<DetailedAddress,String>colDetailedAddress;
    @FXML
    private ComboBox cbGridInspector;
    private ObservableList<FeedbackData> tableList1 = FXCollections.observableArrayList();
    private ObservableList<DetailedAddress> tableList2 = FXCollections.observableArrayList();

    private Map firstMap = new HashMap();
    private Map secondMap = new HashMap();

    private static final List<String> GridInspector_Data = Arrays.asList(
            "11","22","33"
    );

    @FXML
    public void initialize() {
        cbGridInspector.getItems().addAll(GridInspector_Data);

        tableView1.setItems(tableList1);

        colFeedbackerName.setCellValueFactory(new PropertyValueFactory<>("feedbackerName"));
        colEstPollutionLevel.setCellValueFactory(new PropertyValueFactory<>("estPollutionLevel"));
        colFeedbackDate.setCellValueFactory(new PropertyValueFactory<>("feedbackDate"));
        colPhoneNumber.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
        colProvince.setCellValueFactory(new PropertyValueFactory<>("locProvince"));
        colCity.setCellValueFactory(new PropertyValueFactory<>("locCity"));
        colDetails.setCellValueFactory(new PropertyValueFactory<>("details"));

        firstMap = FileUtils.readMapObject("FeedbackData.txt");
        tableList1.addAll(firstMap.values());
        colFeedbackerName.setCellFactory(TextFieldTableCell.forTableColumn());
        colFeedbackerName.setOnEditCommit(event -> {
            FeedbackData c = event.getRowValue();
            String newLocCity = event.getNewValue();
            c.setLocCity(newLocCity);
            firstMap.put(c.getLocCity(), c);
            FileUtils.writeMapObject("FeedbackData.txt", firstMap);
        });

        tableView2.setItems(tableList2);
        colDetailedAddress.setCellValueFactory(new PropertyValueFactory<>("detailedAddress"));
        secondMap = FileUtils.readMapObject("DetailedAddress.txt");
        tableList2.addAll(secondMap.values());
        colDetailedAddress.setCellFactory(TextFieldTableCell.forTableColumn());
        colDetailedAddress.setOnEditCommit(event -> {
            DetailedAddress d = event.getRowValue();
            String newLocCity = event.getNewValue();
            d.setDetailedAddress(newLocCity);
            secondMap.put(d.getDetailedAddress(), d);
            FileUtils.writeMapObject("DetailedAddress.txt", firstMap);
        });
    }

    public void assign() {
        // 获取两个TableView的所有数据行（自动跳过表头）
        ObservableList<FeedbackData> feedbackDataList = tableView1.getItems();
        ObservableList<DetailedAddress> addressDataList = tableView2.getItems();

        // 检查数据是否存在
        if (feedbackDataList.isEmpty() || addressDataList.isEmpty()) {
            AlertUtils.showDialog("warning", "反馈数据或地址数据为空，无法指派");
            return;
        }

        // 读取现有接收数据
        Map<String, ReceivedData> receivedDataMap = FileUtils.readMapObject("gridReceivedData.txt");
        int successCount = 0;

        // 遍历反馈数据，匹配地址数据并处理
        for (FeedbackData feedback : feedbackDataList) {
            // 查找匹配的地址数据（假设通过手机号关联，需根据实际业务调整）
            DetailedAddress matchedAddress = findMatchedAddress(feedback.getPhoneNumber(), addressDataList);

            if (matchedAddress != null) {
                // 从数据行提取信息
                String level = feedback.getEstPollutionLevel();
                String province = feedback.getLocProvince();
                String city = feedback.getLocCity();
                String location = matchedAddress.getDetailedAddress();
                String time = feedback.getFeedbackDate();
                String description = feedback.getDetails();
                String userName = feedback.getFeedbackerName();
                String phoneNumber = feedback.getPhoneNumber();
                String gridInspector = cbGridInspector.getSelectionModel().getSelectedItem() != null
                        ? cbGridInspector.getSelectionModel().getSelectedItem().toString()
                        : "";

                // 创建接收数据对象
                ReceivedData u1 = new ReceivedData(level, province, city, location, time,
                        description, userName, phoneNumber, gridInspector);

                // 保存到Map（手机号作为唯一标识）
                receivedDataMap.put(phoneNumber, u1);
                successCount++;
            }
        }

        // 写入文件
        FileUtils.writeMapObject("gridReceivedData.txt", receivedDataMap);

        // 显示成功提示
        AlertUtils.showDialog("assign", "指派成功，共处理 " + successCount + " 条数据");
    }
    private DetailedAddress findMatchedAddress(String phoneNumber, ObservableList<DetailedAddress> addressList) {
        for (DetailedAddress address : addressList) {
            // 假设地址数据中包含手机号，实际应根据数据模型调整匹配逻辑
            if (address.getDetailedAddress() != null && address.getDetailedAddress().equals(phoneNumber)) {
                return address;
            }
        }
        // 未找到匹配时返回第一条地址数据（示例逻辑，需根据业务调整）
        return addressList.isEmpty() ? null : addressList.get(0);
    }


}
